<?php
namespace app\index\controller;
use think\Controller;

class Base extends Controller {
    private $modelObj;//Category的model变量
    private $currentCity;
    public function _initialize() {
        parent::_initialize();
        //获取分类信息
        $categories = $this->getAllCats();
        $this->assign('categories',$categories);

        //获取城市数据
        $citys = model('City')->getNormalCitys();
        $this->getCity($citys);
        $this->assign('citys',$citys);
        $this->assign('city',$this->currentCity);

        //用户数据
        $this->assign('user',$this->getLoginUser());
    }

    /**
     * 获取当前城市
     * @param $citys
     */
    public function getCity($citys){
        $defaultuname = "guangzhou";
        if(session('cityuname', '', 'index') && !input('get.city')){
            $cityuname = session('cityuname', '', 'index');
        } else {
            $cityuname = input('get.city', $defaultuname, 'trim');
            session('cityuname', $cityuname, 'index');
        }

        $this->currentCity = model('City')->where(['uname'=>$cityuname])->find();
    }

    /**
     * 获取登陆用户数据
     */
    public function getLoginUser(){
        // 获取session来判断是否登陆
        $user = session('yc_user', '', 'user');
        if($user && $user->id){
            return $user;
        }
    }

    public function getAllCats(){
        $catsArr = [];
        $this->modelObj = Model("Category"); //实例化Category的model
        $cats = $this->modelObj->getCategories();//一级分类内容
        foreach ($cats as $cat) {
            $sedcats = $this->modelObj->getCategories($cat->id);
            $tmp = [];
            foreach ($sedcats as $sedcat) {
                $tmp[] = [
                    'id' => $sedcat->id,
                    'name' => $sedcat->name,
                ];
            }
            $catsArr[$cat->id] = [
                'name' => $cat->name,
                'child' => empty($tmp)?[]:$tmp,
            ];
        }
        return $catsArr;
    }
}